/***************************************************************************
 *   Copyright (C) 2006 by Archimedes Projekt   *
 *   thelsb@gmail.com   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "mdataclient.h"
#include <QDataStream>
#include "globals.h"
#include "mcamconblock.h"
#include "mpodconblock.h"
#include "mservconblock.h"
#include "mterrablock.h"

namespace TM {

MDataClient::MDataClient(QObject *parent)
 : QTcpSocket(parent)
 ,m_blockSize(0)
{
 connect(this,SIGNAL(readRead()),this,SLOT(readClient()));
 connect(this,SIGNAL(disconnected()),this,SLOT(deleteLater()));
}


MDataClient::~MDataClient()
{
 //close socket connection before dying
 if(this->state() == QAbstractSocket::ConnectedState)
  this->close();
}


}


/*!
    \fn TM::MDataClient::readClient()
 */
void TM::MDataClient::readClient()
{
    MDataBlock::TYPE blockType = MDataBlock::ERR;
    MDataBlock *dataBlock = NULL;
    QDataStream ins(this);
    //check type of dataBlock
    if(bytesAvailable() < sizeof(blockType))
     return;
    ins>>blockType;
    switch(blockType)
    {
     case MDataBlock::CAMCON: dataBlock = new MCamConBlock;
          break;
     case MDataBlock::PODCON: dataBlock = new MPodConBlock;
          break;
     case MDataBlock::SERVCON: dataBlock = new MServConBlock;
          break;
     case MDataBlock::TERRACON: dataBlock = new MTerraBlock;
          break;
     case MDataBlock::ERR: qWarning("Bad data block TYPE:%d",(int)blockType);
                          return;
          break;
    }
    //wait till a full dataBlock is in the buffer
    if(bytesAvailable() < sizeof(*dataBlock))
    {
     delete dataBlock;
     return;
    }
    //read one dataBlock
    ins>>dataBlock;
}